package com.blackhorse.filters;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义鉴权的全局过滤器，全局过滤器对全部路由route生效
 * 1.名字以XXXXGlobalFilter结尾 2.必须实现GlobalFilter和Ordered接口
 */
@Slf4j
//@Component //启用该全局过滤器时打开此注解
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    /**
     * 过滤器逻辑
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //统一鉴权逻辑，判断请求中是否含有token
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        //token=admin认为鉴权成功
        if (!StringUtils.equals(token, "admin")) {
            //认证失败
            log.warn("认证失败了...");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        //放行
        return chain.filter(exchange);
    }

    /**
     * 定义当前过滤器优先级，值越小优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
